<?php

class CoffeeApplyController extends Controller
{
	const OWNER_ROLE='cafeOwner';
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'roles'=>array('applyAdmin'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(/*'create','update',*/'approve','reject'),
				'roles'=>array('applyAdmin'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'roles'=>array('applyAdmin'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('apply'),
				'users'=>array('@'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new CoffeeApply;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeApply']))
		{
			$model->attributes=$_POST['CoffeeApply'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeApply']))
		{
			$model->attributes=$_POST['CoffeeApply'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('CoffeeApply');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new CoffeeApply('search');
		$model->unsetAttributes();  // clear any default values
		$model->status=DataUtil::STATUS_PENDING;
		if(isset($_GET['CoffeeApply']))
		$model->attributes=$_GET['CoffeeApply'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			$this->_model=CoffeeApply::model()->findByPk($_GET['id']);
			if($this->_model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='coffee-apply-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionApprove()
	{
		$model=$this->loadModel();
		$shop=$model->shop;
		$owner=$model->user;
		$shop->owner=$owner;
		$shop->ownerId=$owner->id;

		if($shop->save()){
			$user=Yii::app()->user;
			$message='';
			if($user->isGuest){
				$message.='Guest User ';
			}else{
				$currentUser=User::model()->findByPk($user->id);
				$message.='User: '.$currentUser->username.' ('.$currentUser->id.') '."\n";
			}
			$message.='Approved owner for cafe: '.$shop->toSummaryString();
			Yii::log($message, CLogger::LEVEL_INFO,'mcr.coffeeshop.apply');
				
				
			$flashMessage="Owner Saved!<br>";
			$model->status=DataUtil::STATUS_APPROVED;
			$model->save();
			$roles=$owner->roles;
			$needAddRole=true;
			if(!empty($roles)){
				foreach ($roles as $role){
					if($role->name==self::OWNER_ROLE){
						$needAddRole=false;
						break;
					}
				}
			}
			if($needAddRole){
				$authManager=Yii::app()->authManager;
				$authManager->assign(self::OWNER_ROLE,$owner->id);
			}
			$absLoginUrl=$this->createAbsoluteUrl('/user/user/login');

			if(!empty($owner->email)){
				Yii::app()->mailer->sendOutgoingMail('approveCafeOwner',$shop->email,'Confirmation of MCR Cafe Claim!',

				array(
					'ownerName'=>$owner->profile->firstname.' '.$owner->profile->lastname,
					'absLoginUrl'=>$absLoginUrl,
					'cafeName'=>$shop->name,
					'email'=>$shop->email,
					'phone'=>$shop->phone,

				));
				$flashMessage.='Email has been sent to '.$owner->email.' to notify about this approval. <br>';
			}
			Yii::app()->user->setFlash('coffee_update',$flashMessage);
		}

		$this->redirect(array('coffeeShop/update',
			'id'=>$shop->id,
		));

	}
	public function actionReject(){
		$model=$this->loadModel();
		$model->status=DataUtil::STATUS_REJECTED;
		if($model->save()){
			$user=Yii::app()->user;
			$message='';
			if($user->isGuest){
				$message.='Guest User ';
			}else{
				$currentUser=User::model()->findByPk($user->id);
				$message.='User: '.$currentUser->username.' ('.$currentUser->id.') '."\n";
			}
			$message.='Rejected owner '.$model->user->username.' for cafe: '.$model->shop->name;
			Yii::log($message, CLogger::LEVEL_INFO,'mcr.coffeeshop.apply');
				
			if(!empty($model->user->email)){
				Yii::app()->mailer->sendOutgoingMail('rejectCafeOwner',$model->user->email,'MCR Cafe Claim: Unsuccessful',

				array(
					'ownerName'=>$model->user->profile->firstname.' '.$model->user->profile->lastname,
				//'absLoginUrl'=>$absLoginUrl,
					'cafeName'=>$model->shop->name,
				//'email'=>$shop->email,
				//'phone'=>$shop->phone,
				));
				//$flashMessage.='Email has been sent to '.$email.' to notify about this approval. <br>';
			}
			$this->redirect(array('admin'));
		}
	}

	public function actionApply()
	{
		$user=Yii::app()->user;
		$model=new CoffeeApply('applyOwner');
		if(!isset($_GET['id'])){
			$user->setFlash('coffeeApply','Please choose a cafe first!');
			$this->render('apply',array('model'=>$model));
			return;
		}
		$coffeeShop=intval($_GET['id']);
		$shop=CoffeeShop::model()->findByPk($coffeeShop);
		if(!$shop){
			$user->setFlash('coffeeApply','This cafe does not exist!');
			$this->render('apply',array('model'=>$model));
			return;
		}

		if($user->getIsGuest()){
			$user->loginRequired();
			Yii::app()->end();
			return;
		}
		$user_id=$user->getId();

		// uncomment the following code to enable ajax-based validation
		/*
		if(isset($_POST['ajax']) && $_POST['ajax']==='coffee-apply-apply-form')
		{
		echo CActiveForm::validate($model);
		Yii::app()->end();
		}
		*/


		if(isset($_POST['CoffeeApply']))
		{
			$model->user_id=$user_id;
			$model->shop_id=$shop->id;
			$model->applyTime=time();
			$model->status=DataUtil::STATUS_PENDING;
			$model->comment=$_POST['CoffeeApply']['comment'];
			if($model->save()){
					
				@Yii::app()->mailer->sendOutgoingMail('alertEmail',Yii::app()->params['alertEmail'],'Auto Alert: cafe owner apply',
				array(
					'event'=>array(
						'event'=>'A user claims to be owner of cafe',
						'user email'=>$model->user->email,
						'name'=>$model->shop->name
				)
				));
					
				$user->setFlash('coffeeApply','Thank you for your application. We will proceed it as soon as possible. <br />Now redirecting to payment page...');
				$url=$this->createUrl('subscribe/cafeOwnerPay',array('id'=>$shop->id));
				Yii::app()->clientScript->registerScript("jumpOrderRedirect",
			'setTimeout("window.location = \''.$url.'\'",4000)');
			}
				
		}
		$this->render('apply',array('model'=>$model,'coffeeShop'=>$shop));
	}
}
